﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using CoolERP_BLL;

namespace CoolERP_Web
{
    public class Utility
    {
        #region=======全局常量=======
        /// <summary>
        /// 分厂号
        /// </summary>
        public static string FactoryBH = "01";
        /// <summary>
        /// 新增用户时的初始密码
        /// </summary>
        public static string Password = "123456";
        /// <summary>
        /// 缓存URL <-> CODE 对应关系Key
        /// </summary>
        public static string UrlCacheKey = "Url_Code";
        public static string InventoryPath = "/UploadFiles/Inventory/";
        #endregion

        /// <summary>
        /// 是否开启权限检查
        /// </summary>
        /// <returns></returns>
        public static bool IsCheckPermission()
        {
            CacheManager cache = new CacheManager();
            string cacheKey = "IsCheckPermission";
            if (!cache.Exist(cacheKey))
            {
                string keyVal = SystemParamBLL.GetParamByKey("IsCheckPermission");
                if (string.IsNullOrEmpty(keyVal))
                    keyVal = "false";
                cache.Add(cacheKey, keyVal);
            }
            return Convert.ToBoolean(cache.Get(cacheKey));
        }
        /// <summary>
        /// 生成空格
        /// </summary>
        public static string GenSpace(int values)
        {
            string space = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            string retString = string.Empty;
            for (int i = 0; i < values; i += 4)
                retString += space;
            return retString;
        }

        /// <summary>
        /// 合并GridView中相同信息的行（多列相同）
        /// </summary>
        public static void MergeCols(GridView grv, List<int> cols)
        {
            if (grv.Rows.Count < 1)
                return;
            for (int i = 0; i < grv.Rows.Count - 1; )
            {
                TableRow oldTr = grv.Rows[i];
                bool isSame = true;
                for (int j = i + 1; j < grv.Rows.Count; j++)
                {
                    i = j;
                    TableRow tr = grv.Rows[j];
                    foreach (int k in cols)
                    {
                        if (oldTr.Cells[k].Text != tr.Cells[k].Text)
                        {
                            isSame = false;
                            break;
                        }
                    }
                    if (isSame)
                    {
                        foreach (int k in cols)
                        {
                            TableCell oldTc = oldTr.Cells[k];
                            TableCell tc = tr.Cells[k];
                            tc.Visible = false;
                            if (oldTc.RowSpan == 0)
                                oldTc.RowSpan = 1;
                            oldTc.RowSpan++;
                            oldTc.VerticalAlign = VerticalAlign.Middle;
                        }
                    }
                    else
                        break;
                }
                if (!isSame)
                    continue;
            }
        }

        /// <summary>
        /// 空记录时仍然显示GridView
        /// </summary>
        /// <param name="grv"></param>
        /// <param name="fieldnames"></param>
        public static void RenderEmptyGridView(GridView grv, string fieldnames)
        {
            //将gridview变成只有header和footer列，以及被隐藏的空白资料列   
            DataTable dt = new DataTable();
            string[] colname = fieldnames.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string mycol in colname)
                dt.Columns.Add(new DataColumn(mycol));
            DataRow dr = dt.NewRow();
            foreach (string mycol in colname)
                dr[mycol] = DBNull.Value;
            dt.Rows.Add(dr);
            grv.DataSourceID = null;
            grv.DataSource = dt;
            grv.DataBind();
            grv.Rows[0].Visible = false;
        }

        /// <summary>
        /// 是否图片
        /// </summary>
        public static bool IsImage(string strFile)
        {
            bool isOK = false;

            // 1) 获取上传文件的后缀名，检查是否允许上传的格式
            string file_extension = System.IO.Path.GetExtension(strFile).ToLower();
            //能支持的后缀名
            string[] all_extension = { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };

            for (int i = 0; i < all_extension.Length; i++)
            {
                if (file_extension == all_extension[i])
                    isOK = true;
            }

            if (isOK)
            {
                // 2) 如果没有Directory目录就创建
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(strFile));

                // 3) 如果存在文件FileName，则删除
                if (System.IO.File.Exists(strFile))
                {
                    System.IO.FileInfo _fileInfo = new System.IO.FileInfo(strFile);
                    _fileInfo.IsReadOnly = false;
                    System.IO.File.Delete(strFile);
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public static void DeleteFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    //FileInfo _fileInfo = new FileInfo(path);
                    //_fileInfo.IsReadOnly = false;
                    File.Delete(path);
                }
            }
            catch { }
        }

        /// <summary>
        /// 生成图片名字（按时间）
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static string GenFileName(string FileName)
        {
            return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssffff"), System.IO.Path.GetExtension(FileName));
        }

        #region==========上传图片，生成缩略图==========
        /// <summary>   
        /// 生成缩略图
        /// </summary>   
        /// <param name="originalImagePath">源图路径（物理路径）</param>   
        /// <param name="fileSaveUrl">保存路径（物理路径）</param>   
        /// <param name="width">缩略图宽度</param>   
        /// <param name="height">缩略图高度</param>   
        /// <param name="mode">生成缩略图的方式(mode："W"[指定宽，高按比例]，"H"[指定高，宽按比例]，"HW"[指定高宽缩放（如不按比例可能变形）]，"CUT"[指定高宽按比例裁减（不变形）]</param>           
        public static string MakeMiniature(HttpPostedFile postFile, string fileSaveUrl, System.Double width, System.Double height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(postFile.InputStream, true);
            try
            {
                string fileName = GenFileName(System.IO.Path.GetExtension(postFile.FileName));
                if (originalImage.Width <= width && originalImage.Height <= height)
                {
                    fileSaveUrl += fileName;
                    if (IsImage(fileSaveUrl))
                        postFile.SaveAs(fileSaveUrl);
                }
                else
                {
                    fileSaveUrl += fileName;
                    if (IsImage(fileSaveUrl))
                        SaveImage(postFile.InputStream, fileSaveUrl, width, height, mode);
                }
                return fileName;
            }
            catch (Exception err)
            {
                return string.Empty;
            }
            finally
            {
                originalImage.Dispose();
            }
        }

        private static void SaveImage(System.IO.Stream fromFileStream, string fileSaveUrl, System.Double width, System.Double height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(fromFileStream, true);

            System.Double towidth = width;
            System.Double toheight = height;
            System.Double x = 0;
            System.Double y = 0;
            System.Double ow = originalImage.Width;
            System.Double oh = originalImage.Height;

            #region==========按指定模式确定宽高==========
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）    
                    #region==========执行下面语句则不变形，否则裁减后变形==========
                    //宽大于模版的横图
                    if (originalImage.Width >= originalImage.Height)
                    {
                        if (originalImage.Width > towidth)
                        {
                            //宽按模版，高按比例缩放
                            //towidth = towidth;
                            toheight = originalImage.Height * (towidth / originalImage.Width);
                        }
                    }
                    else//高大于模版的竖图
                    {
                        if (originalImage.Height > toheight)
                        {
                            //高按模版，宽按比例缩放
                            //toheight = toheight;
                            towidth = originalImage.Width * (toheight / originalImage.Height);
                        }
                    }
                    #endregion====================
                    break;
                case "W"://指定宽，高按比例                                           
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例   
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "CUT"://指定高宽裁减（不变形）                                   
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            #endregion

            //取得图片大小
            System.Drawing.Size mySize = new System.Drawing.Size((int)towidth, (int)toheight);
            //新建一个bmp图片   
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
            //新建一个画板   
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法   
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度   
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充   
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分   
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle((int)x, (int)y, (int)ow, (int)oh), System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图   
                bitmap.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception err)
            {
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        #endregion
    }
}